<?php

namespace App\Http\Controllers\Owner;

use App\Models\Member;
use App\Traits\Msg;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Validator;

class LoginController extends Controller
{

    use Msg;

    /**登录逻辑
     * @param Request $request
     */
    public function login(Request $request)
    {
        $phone = $request->post('phone');
        $captcha = $request->post('captcha');
        $role_id = $request->post('user_type', 20);//10司机，20货主

        try {
            $validator = Validator::make($request->all(), [
                'phone' => 'required|numeric|regex:/^1[3456789][0-9]{9}$/',
                'captcha' => 'required',
            ], ['required' => ':attribute必须填写'], ['mobile' => '手机号', 'captcha' => '验证码']);

            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
               if (!$this->verifyMsgCode($phone, $captcha)) {
                    return $this->error('验证码已失效或者错误');
                }
            try {
                $user = Member::query()->where('phone', $phone)->where('role_id', $role_id)->where('status', 1)->firstOrFail();
            } catch (\Exception $es) {
                return $this->error('账号不存在');
            }
            $memberModel = new Member();
            $role_text = $memberModel->changeRoleText($role_id);
            if (!$user) {
                return $this->error('该' . $role_text . '未注册');
            }
            session_start();
            $_SESSION['ownerpc'] = ['ownerpcuserid' => $user->id, 'uuid' => $user->uuid, 'phone' => $user->phone];
            return $this->success('登录成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

    }

    /**
     * 用于登录的字段
     * @return string
     */
    public function phone()
    {
        return 'phone';
    }

    public function showLoginForm(Request $request)
    {
        $errors = [];

        return view('owner.login_register.login', compact('errors', $errors));
    }

    public function loginout(Request $request)
    {
        session_start();
        if (isset($_SESSION['ownerpc'])) {
            unset($_SESSION['ownerpc']);
        }

        return redirect(route('owner.ownerForm'));


    }
}
